package com.tedu.firstspringboot.controller;

import com.tedu.firstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class UserController {
    private static File userDir;
    static {
        userDir=new File("./users");
        if(!userDir.exists()){
            userDir.mkdir();
        }
    }
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        System.out.println("helloworld");
        String username = httpServletRequest.getParameter("username");
        String userpwd = httpServletRequest.getParameter("userpwd");
        String userage = httpServletRequest.getParameter("age");
        String nikename = httpServletRequest.getParameter("nikename");

        if(username==null||username.trim().isEmpty()||
                userpwd==null||userpwd.trim().isEmpty()||
                nikename==null||nikename.trim().isEmpty()||
                userage==null||userage.trim().isEmpty()||
                !userage.matches("[0-9]+")){
            try {
                httpServletResponse.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        System.out.println(username+","+userpwd+","+userage+","+nikename);
        int age =Integer.parseInt(userage);
        User user=new User(username,userpwd,nikename,age);
        File file=new File(userDir,username+".obj");
        if(file.exists()){
            try {
                httpServletResponse.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try(
        FileOutputStream fos=new FileOutputStream(file);
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            httpServletResponse.sendRedirect("/reg_success.html");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
